package org.fatmansoft.teach.security.jwt;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import org.fatmansoft.teach.security.services.UserDetailsServiceImpl;

public class AuthTokenFilter extends OncePerRequestFilter {  //保证请求只会经过过滤器一次
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
//            获取token
            String jwt = parseJwt(request);
//            解析token
            if (jwt != null && jwtUtils.validateJwtToken(jwt)) { //验证jwt令牌是否有效
//                获取用户信息
                String username = jwtUtils.getUserNameFromJwtToken(jwt);
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
//                将用户信息封装为UsernamePasswordAuthenticationToken
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

//                传入SecurityContextHolder，便于后续filter访问认证
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            logger.error("Cannot set user authentication: {0}", e);
        }

        filterChain.doFilter(request, response);  //进行放行
    }

    private String parseJwt(HttpServletRequest request) {
//        从前端的请求头中获取Authorization信息
        String headerAuth = request.getHeader("Authorization");

        if (StringUtils.hasText(headerAuth)) {
//        将获取的Authorization信息转化为JSON格式
            JSONObject json = (JSONObject) JSONObject.parse(headerAuth);
            try{
                String tokenType = json.get("tokenType").toString(); //获取Token的类型
                if (tokenType.equals("Bearer")) {  //类型匹配
                    String jwt = json.get("accessToken").toString();  //获取Token
                    return jwt;  //返回解析到的jwt
                }
            }catch (Exception e){
            }
        }

        return null;
    }
}
